﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Olemas.DataModels;
using Olemas.Models;
using Olemas.ViewModels;

namespace Olemas.Controllers
{
    public class CommentsController : Controller
    {
        private const int PageSize = 4;
        
        /// <summary>
        /// Displays the comments posted to the item with the given Id and type
        /// </summary>
        /// <param name="page">The page of comments to be loaded.</param>
        /// <param name="itemId">The Id of the item to display comments for.</param>
        /// <param name="typeId">The type Id of the item to display comments for (1=book,2=conspect,3=test).</param>
        public ActionResult Comments(int page, int itemId, int typeId)
        {
            // Get comments with provided ID´s
            var comments = CommentModel.GetComments(itemId, typeId, page, PageSize) as IEnumerable<Comment>;
            var totalPages = 0;
            var pagesRemaining = "";

            // If there aren't any comments the following values are not calculated from db.
            if (comments.Any())
            {
                var commentsTotal = CommentModel.GetNumberOfComments(itemId, typeId);
                totalPages = GlobalViewModel.GetTotalPages(commentsTotal, PageSize);
                pagesRemaining = GlobalViewModel.RemainingPages(totalPages, page);
            }

            var commentsViewModel = new CommentsViewModel(comments, totalPages, itemId, typeId, page, pagesRemaining);

            if (Request.IsAjaxRequest())
            {
                return PartialView("_DisplayedComments", commentsViewModel);
            }

            return PartialView("_Comments", commentsViewModel);
        }
       

        /// <summary>
        /// Adds a comment to the database.
        /// </summary>
        /// <param name="comment">The comment object being added.</param>
        [HttpPost]
        public ActionResult AddComment(Comment comment)
        {
            if (ModelState.IsValid)
            {
                CommentModel.AddCommentToDb(comment);
            }
            return RedirectToAction("Comments", new {page = 1, itemId = comment.ItemId, typeId = comment.ItemType});
        }


    }
}
